import { TOKEN } from '@/common/constant'
import { useGetLocalStorage } from '@/hooks/useLocalStorage'
import { message } from 'antd'
import axios from 'axios'
import { HTTP_PATH } from '@/common/http-url'

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_PROXY_PATH + HTTP_PATH,
  timeout: 10000,
  withCredentials: true
})

console.log(import.meta.env.VITE_APP_PROXY_PATH);


request.interceptors.request.use(
  (config) => {
    let local = useGetLocalStorage(TOKEN)
    if (local && local.token)
      config.headers.Authorization = `Bearer ${local.token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response.status === 401) {
      message.error('登录已过期，请重新登录。')
      setTimeout(() => {
        window.location.href = '/login'
      }, 1000)
      return
    }
    error.response &&
      message.error(error.response.data.message ?? '请求失败，请稍后再试。')
    return Promise.reject(error)
  }
)

export default request
